package Main.Controller;

import Main.BaiduTools.Base64Util;
import Main.BaiduTools.FileUtil;
import Main.BaiduTools.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

@Controller
public class getPic {
    @ResponseBody
    @RequestMapping(value = "/picInfo")
    public JSONObject request(@RequestParam("picmsg") String picmsg) {
        JSONObject object = new JSONObject();
        String url = "https://aip.baidubce.com/rest/2.0/image-classify/v2/advanced_general";
        try {
            //把图片解码
            //String filePath = "D:/box.jpg";
            //byte[] imgData = FileUtil.readFileByBytes(filePath);
            //String imgStr = Base64Util.encode(imgData);
            String imgParam = URLEncoder.encode(picmsg, "UTF-8");
            String param = "image=" + imgParam;

            // 从百度那里申请到的access_token，有可能过期,记得申请
            String accessToken = "24.8254a6846bf5faaf0c6624b2331f1f2b.2592000.1603196551.282335-22563553";
            //接受我的POST请求吧！百度桑！
            String result = HttpUtil.post(url, accessToken, param);
            System.out.println(result);
            object = JSONObject.parseObject(result);
            //return object;
        } catch (Exception e) {
            e.printStackTrace();
        }

       /*
       * 下面就是把getInfoRequest函数整合到这里边而已
       * */
        String httpUrl = "http://api.tianapi.com/txapi/lajifenlei/index?key=436036e6177d1b5f93c17e7932962bf2&word=";
        String item[] = new String[5];//图像识别最多识别出5个对象
        JSONArray tempArr = new JSONArray();
        tempArr = object.getJSONArray("result");
        JSONObject resultJson = new JSONObject();
        /*
        * 百度会帮你识别出五个对象
        * */
        for (int i = 0; i<5 && i<Integer.parseInt(object.get("result_num").toString()); i++ ){
            JSONObject temp = tempArr.getJSONObject(i);
            item[i] = temp.get("keyword").toString();
            String tempURL = httpUrl + item[i];
            BufferedReader reader = null;
            StringBuffer sbf = new StringBuffer();
            try {
                URL tempurl = new URL(tempURL);
                HttpURLConnection connection = (HttpURLConnection) tempurl
                        .openConnection();
                connection.setRequestMethod("GET");
                InputStream is = connection.getInputStream();

                String result = null;
                reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                String strRead = null;
                while ((strRead = reader.readLine()) != null) {
                    sbf.append(strRead);
                    sbf.append("\r\n");
                }
                reader.close();
                result = sbf.toString();
                //这个tempJSON就是垃圾分类帮你判断出的一个东西
                JSONObject tempJSON = JSONObject.parseObject(result);

                resultJson.put(""+i, tempJSON);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }//for
        //从最后的返回结果提取出所有的物品及类别
        int num = 0;
        JSONObject returnJson = new JSONObject();
        JSONArray finArr = new JSONArray();
        for(int i = 0; resultJson.get(Integer.toString(i))!=null; i++ ){
            String strInt = Integer.toString(i);
            JSONObject temp = JSONObject.parseObject(resultJson.get(strInt).toString());
            if(Integer.parseInt(temp.get("code").toString())!=200){
                resultJson.remove(strInt);
            }else{
                JSONArray arr = new JSONArray();
                JSONObject numObj = resultJson.getJSONObject(strInt);
                arr = numObj.getJSONArray("newslist");
                for(int j = 0; j < arr.size(); j++){
                    String name = arr.getJSONObject(j).get("name").toString();
                    String type = arr.getJSONObject(j).get("type").toString();
                    JSONObject tempJson = new JSONObject();
                    tempJson.put("name", name); tempJson.put("type", type);
                    finArr.add(tempJson);

                    num++;
                }
            }
            returnJson.put("list", finArr);
        }
        return returnJson;
    }
/*
    private static JSONObject getInfoRequest(JSONObject object){
        String httpUrl = "http://api.tianapi.com/txapi/lajifenlei/index?key=436036e6177d1b5f93c17e7932962bf2&word=";
        String item[] = new String[5];
        JSONArray tempArr = new JSONArray();
        tempArr = object.getJSONArray("result");
        JSONObject resultJson = new JSONObject();
        for (int i = 0; i<5 && i<Integer.parseInt(object.get("result_num").toString()); i++ ){
            JSONObject temp = tempArr.getJSONObject(i);
            item[i] = temp.get("keyword").toString();
            String tempURL = httpUrl + item[i];
            try {
                URL url = new URL(tempURL);
                HttpURLConnection connection = (HttpURLConnection) url
                        .openConnection();
                connection.setRequestMethod("GET");
                InputStream is = connection.getInputStream();
                BufferedReader reader = null;
                StringBuffer sbf = new StringBuffer();
                String result = null;
                reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                String strRead = null;
                while ((strRead = reader.readLine()) != null) {
                    sbf.append(strRead);
                    sbf.append("\r\n");
                }
                reader.close();
                result = sbf.toString();
                JSONObject tempJSON = JSONObject.parseObject(result);
                resultJson.put(""+i, tempJSON);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return resultJson;
    }*/
}
